<?php

class Silk_Mapi_Model_Observer
{
    const YII_URI = 'http://api.hahahui.cn';

    protected $_http_client;

    protected function _http() {

        if (!$this->_http_client) {

            require_once "Zend/Http/Client.php";

            $this->_http_client = new Zend_Http_Client;
        }

        return $this->_http_client;

    }

    public function synchronizeToYii(Varien_Event_Observer $observer)
    {
        $customer = $observer->getCustomer();
        $addresses = $customer->getAddresses();
        if(count($addresses))
        {
            $address = $addresses[0];
        }
        else
        {
            $address = Mage::getModel('customer/address');
        }
        $mobile = explode('@', $customer->getEmail());
        /*$store = array(
            'name' => $customer->getLastname(),
            'address' => $address->getStreetFull(),
            'phone' => $address->getTelephone(),
            'owner' => $address->getFirstname(),
            'code' => $customer->getId(),
        );*/
        $data = array(
            'username' => $customer->getFirstname(),
            'password' => $customer->getPasswordHash(),
            'mobile' => $mobile[0],
            'magentoId' => $customer->getId(),
            'siteId' => $customer->getWebsiteId(),
            //'store' => $store,
        );

        Mage::log($data);

        $pushUrl = Mage::helper('mapi')->getenv('DITUI_API_URL', self::YII_URI).'/synchronizes/customers';
        $pushUrl = Mage::getStoreConfig('general/api/customer_push_url');
        $pushUrl = trim($pushUrl,'/').'/synchronizes/customers';
        Mage::log($pushUrl, null, 'api_sync.log');


        $response = $this->_http()
            ->setUri($pushUrl)
            ->setParameterPost($data)
            ->request(Zend_Http_Client::POST);

        Mage::log($response->getStatus().'-----'.$response->getBody(), null, 'api_sync.log');
    }

    public function updateProductCache(Varien_Event_Observer $observer)
    {
        //$product = $observer->getProduct();
        //if($product) Mage::helper('mapi/cache')->updateProduct($product);
    }
}